<?php
namespace app\modules\api\controllers;

use Yii;
use yii\db\Expression;
use app\models\Config;
use app\models\Member;
use app\models\OrderInfo;
use app\models\OrderInfoSearch;
use app\models\Goods;
use app\models\GoodsSearch;
use app\models\GoodsCategory;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use yii\helpers\Html;


class OrderController extends AuthController
{

    /*添加订单*/
    public function actionAddOrder()
    {
        if(Yii::$app->request->isPost){
            // P(json_decode($this->post['OrderInfo']));
            $mid = $this->userInfo->member_id;

            /*整理数据*/
            $this->post['OrderInfo'] = (array)json_decode($this->post['OrderInfo']);
            for($i =  0; $i < count($this->post['OrderInfo']['goodsInfo']); $i++) {
                $this->post['OrderInfo']['goodsInfo'][$i] = (array)$this->post['OrderInfo']['goodsInfo'][$i];
                if($this->post['OrderInfo']['goodsInfo'][$i]['preview']) {
                    for($j = 0; $j < count($this->post['OrderInfo']['goodsInfo'][$i]['preview']); $j++) {
                        $this->post['OrderInfo']['goodsInfo'][$i]['preview'][$j] = (array)$this->post['OrderInfo']['goodsInfo'][$i]['preview'][$j];
                    }
                }
            }
            // P($this->post['OrderInfo']);

            $pass = true;
            /*验证数据*/
            // if(!isset($this->post['OrderInfo']['deliver_id']) or 
            //     empty($this->post['OrderInfo']['deliver_id'])) {
            //     $backInfo = ErrMap::getError(10005, "请选择收货地址");//返回信息
            //     $pass = false;
            // }
            foreach($this->post['OrderInfo']['goodsInfo'] as $k => $v) {
                if($v['catid'] == "") {
                    $backInfo = ErrMap::getError(10005, "请选择分类");//返回信息
                    $pass = false;
                }
                if($v['name'] == "") {
                    $backInfo = ErrMap::getError(10005, "请填写鉴品名称");//返回信息
                    $pass = false;
                }
            }

            /* 如果是老师鉴定，需要选择老师 */
            if(isset($this->post['OrderInfo']['auth_type']) and 
                $this->post['OrderInfo']['auth_type'] == 3 and 
                $this->post['OrderInfo']['experts_id'] == 0) {
                $backInfo = ErrMap::getError(10005, "请选择老师");//返回信息
                $pass = false;
            }

            /* 根据鉴定方式，取出鉴定金额 */
            $money = 0;
            $config = Config::find()->one();
            // P($config);
            if($this->post['OrderInfo']['auth_type'] == 1) {//图片鉴定
                $money = $config->photo_auth_cost;
            } else if($this->post['OrderInfo']['auth_type'] == 2) {//邮寄鉴定
                $money = $config->mail_auth_cost;
            } else if($this->post['OrderInfo']['auth_type'] == 3) {//老师鉴定
                $money = $config->expert_auth_cost;
            }
            if($money == 0) {
                $backInfo = ErrMap::getError(10005, "鉴定方式有误");//返回信息
                $pass = false;
            }
            $money = $money * 100;
            $this->post['OrderInfo']['order_amount'] = $money;
            $this->post['OrderInfo']['member_id'] = $mid;

            /*如果是账户支付，验证余额*/
            if(isset($this->post['OrderInfo']['pay_mode']) and $this->post['OrderInfo']['pay_mode'] == 1) {
                $info = Member::find()->select(['account', 'nickname', 'headimgurl', 'add_time'])
                      ->where('member_id = :id', [':id' => $mid])
                      ->one();
                // P($info);
                if($info->account < $this->post['OrderInfo']['order_amount']) {
                    $backInfo = ErrMap::getError(10005, "余额不足");//返回信息
                    $pass = false;
                }
                $this->post['OrderInfo']['pay_status'] = 3;
            }

            $resData = "";//返回的数据，主要是要返回订单的ID
            if($pass) {
                $orderInfo = new OrderInfo;
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                try{
                    /*1、添加备案*/
                    if(!$order_id = $orderInfo->addOrder($this->post)){
                        $pass = false;
                        if($orderInfo->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $orderInfo->getErrors();//异常信息
                        }else{
                            throw new \Exception('添加备案失败');
                        }
                    }
                    $resData = $order_id;
                    // P($order_id);
                    if($pass) {
                        $num = count($this->post['OrderInfo']['goodsInfo']);
                        for($i = 0; $i < $num; $i++) {
                            /*2、添加鉴品*/
                            $goods = new Goods;
                            $data = [
                                "Goods" => $this->post['OrderInfo']['goodsInfo'][$i]
                            ];
                            $data["Goods"]["order_id"] = $order_id;
                            $data["Goods"]["member_id"] = $mid;
                            // P($data);
                            if(!$goods_id = $goods->addGoods($data)){
                                $pass = false;
                                if($goods->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $goods->getErrors();//异常信息
                                }else{
                                    throw new \Exception('添加备案失败');
                                }
                            }

                            /*3.增加此分类的鉴品数量， 其他分类不增加*/
                            GoodsCategory::updateAllCounters(['content_count' => 1], 'catid = :id', [':id' => $this->post['OrderInfo']['goodsInfo'][$i]['catid']]);
                        }
                    }

                    if($pass) {
                        /*如果是余额支付，扣款*/
                        if(isset($this->post['OrderInfo']['pay_mode']) and 
                            $this->post['OrderInfo']['pay_mode'] == 1) {
                            Member::updateAllCounters(['account' => -$money], 'member_id = :id', [':id' => $mid]);
                        }
                    }

                    if($pass){
                        $backInfo = [0, '添加备案成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };
            }
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception, $resData) ) != 'boolean'){
            return $res;
        };
    }



}
